package com.system.manager.modules.assit.controller;


import com.system.manager.common.annotation.CurrSubject;
import com.system.manager.common.annotation.PreAuthorize;
import com.system.manager.common.entity.PageDTO;
import com.system.manager.common.entity.Result;
import com.system.manager.modules.assit.entity.Notice;
import com.system.manager.modules.assit.service.INoticeService;
import com.system.manager.modules.authorized.entity.Subject;
import com.system.manager.modules.authorized.enums.AuthorizationErrorCode;
import com.system.manager.modules.authorized.enums.SubjectType;
import com.system.manager.modules.authorized.exception.AuthorizationException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yxp
 * @since 2021-11-25
 */
@Api(tags = "公告API")
@RestController
@RequestMapping("/assit/notice/")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;


    @PreAuthorize(SubjectType.ANONYMOUS)
    @ApiOperation("发布公告")
    @PostMapping("insert")
    public Result publish(@RequestBody Notice notice, @CurrSubject Subject subject){

        notice.setRole(subject.getType().getType());
        notice.setUserId(subject.getId());
        noticeService.publish(notice);

        return Result.ok();
    }

    @PreAuthorize(SubjectType.ANONYMOUS)
    @ApiOperation("查看当前角色已发布的公告")
    @GetMapping("select/all/page")
    public PageDTO selectAll(@RequestParam(name = "page", required = false, defaultValue = "1")Integer page,
                            @RequestParam(name = "limit", required = false, defaultValue = "10")Integer size,
                            @CurrSubject Subject subject){

        PageDTO<Notice> noticeList= noticeService.selectByUId(page, size, subject.getId());

        return noticeList;
    }

    @PreAuthorize(SubjectType.ANONYMOUS)
    @ApiOperation("查看公告内容")
    @GetMapping("select/{aId}")
    public Result selectNotice(@PathVariable("aId")Integer aId){

        Notice notice = noticeService.getById(aId);

        return Result.ok(notice);
    }

    @PreAuthorize(SubjectType.ANONYMOUS)
    @ApiOperation("更改公告内容")
    @PostMapping("save")
    public Result saveNotice(@RequestBody Notice notice){

        noticeService.updateById(notice);

        return Result.ok();
    }
    @PreAuthorize(SubjectType.ANONYMOUS)
    @ApiOperation("在加载welcome时，加载对应的公告")
    @GetMapping("welcome")
    public Result selectWelcomeNotice(@CurrSubject Subject subject){

        Map<String, Object> map = noticeService.selectByRole(subject.getType().getType());

        return Result.ok(map);
    }
}
